package kotan.server.embedded;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Logger;

import kotan.AppEngineEnv;

/**
 * 
 * @author shuji.w6e
 * @since 1.0
 */
public class DevAppServer {

    /** logger */
    private static Logger logger = Logger.getLogger(DevAppServer.class.getName());
    
    /** server process */
    private final DevAppServerProcess process;
    final AppEngineEnv env;
    private final ExecutorService service;

    public DevAppServer(AppEngineEnv env) {
        this.env = env;
        process = new DevAppServerProcess(this);
        service = Executors.newSingleThreadExecutor();
    }

    public synchronized void start() throws ServerStartupException {
        try {
            process.start();
            service.submit(new Runnable() {

                @Override
                public void run() {
                    try {
                        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                        while (true) {
                            String line = reader.readLine();
                            if (line == null) break;
                            logger.fine(line);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        } catch (IOException e) {
            throw new ServerStartupException(e);
        }
    }

    public synchronized void shutdown() {
        service.shutdownNow();
        process.kill();
    }

    @Override
    protected void finalize() throws Throwable {
        shutdown();
    }

}
